#-*- coding: utf-8 -*-
#! /usr/bin/python

import urllib
import urllib2
import time
import socket
from browser_bogus import Browser

def logd(content,fname = "sysrun.log",dolog = True):
    if dolog:
        try:
            if fname == None:
                fname = "sysrun.log"
            fp = open(fname, "a")
            fp.write(content)
            fp.close()
            return True
        except IOError:
            print "log err"
            return False
    else:
        return True
    
    
def getcontent(url,user,retrytime=5):
    request = urllib2.Request(url)
    clen = 0
    i = 1
    while clen < 10:
        try:
            result = user.urlOpener.open(request)
            content = result.read();
            clen = len(content)
            if i > 1:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk') + "读取错误，休眠5秒后重试".decode("utf-8").encode('gbk') + "\r\n")
            time.sleep(retrytime)
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
            logd(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+ "===========" + '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk') + "连接超时，休眠5秒后重试".decode("utf-8").encode('gbk') + "\r\n")
            time.sleep(retrytime)
        i += 1
    return content


def getpostcontent(url,user,logindata):
    en_logindata = urllib.urlencode(logindata)
    request = urllib2.Request(url, en_logindata)
    request.add_header("User-Agent", user.user_agent)
    request.add_header("Referer", "http://nari.21tb.com/els/html/course/course.frame.do#index")
    clen = 0
    i = 1
    while clen < 10:
        try:
            result = user.urlOpener.open(request)
            content = result.read();
            clen = len(content)
            if i > 1:
                print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试成功'.decode('utf-8').encode('gbk')
        except urllib2.URLError:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        except socket.timeout:
            print '第'.decode('utf-8').encode('gbk') + str(i+1) +'次重试失败'.decode('utf-8').encode('gbk')
        i += 1
        #解决某些没有返回值的情况
        if clen == 0:
            break
    
    return content
    
    
